﻿using Dapper;
using DB.EF;
using EF.DB;
using MySqlConnector;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations.Schema;
using System.Data;
using System.Data.SQLite;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using static DB.Dapper.SQLLib;


//引入：Pomelo.EntityFrameworkCore.MySql
//引入：Dapper.Contrib
namespace DB.Dapper
{
    public class DapperUtilsForMysql
    {
        private static SQLDialect sQLDialect = SQLLib.SQLDialect.MySQL;

        public static string queryObject(string sql, object parameters = null)
        {
            using (var conn = new MySqlConnection(DbConnStr.connStr))
            {
                string result = conn.QueryFirstOrDefault<string>(sql, parameters);
                return result;
            }
        }




        public static async Task<List<T>> queryList<T>(string sql, object parameters = null, string sort = "", string where = null,int? topNum=null) where T : class
        {
            using (var conn = new MySqlConnection(DbConnStr.connStr))
            {
                
                string allSql = SQLLib.ListSQLZjc(sql, where, sort);
                if (topNum != null)
                {
                    allSql = allSql + " LIMIT " + topNum;
                }
                IEnumerable<T> list = await conn.QueryAsync<T>(allSql, parameters);
                return list.ToList();
            }
        }
        /// <summary>
        /// 分页组件
        /// </summary>
        /// <param name="act">返回的结果函数</param>
        /// <param name="mainSql">主sql</param>
        /// <param name="pageNumber">当前页</param>
        /// <param name="pageSize">每页条数</param>
        /// <param name="sort">排序</param>
        /// <param name="where">查询条件</param>
        /// <param name="parameters">查询条件参数</param>
        public static List<T> PaginationZjc<T>(string mainSql, int pageNumber, int pageSize, ref int total,
           string sort = "",string where = null, object parameters = null)where T : new()
        {
            //using (var conn = new SqlConnection(DbConnStr.connStr)) //sqlserver 的
            using (var conn = new MySqlConnection(DbConnStr.connStr))
            {
                
                string sql = SQLLib.PaginationSQLZjc(sQLDialect, mainSql, pageNumber, pageSize, where, sort);
                string countSql = SQLLib.CountSQLZjc(mainSql, where);
                List<T> list =  conn.Query<T>(sql, parameters).ToList();
                total = conn.QueryFirstOrDefault<int>(countSql,parameters);
                return list;
            }
        }





    }
}
